<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: SuperMan <mp5a6mg@163.com>
// +----------------------------------------------------------------------
use think\Db;

// 应用公共文件
function ItkeeGetTheme() {
    return HOME_THEMES_NAME;
}

/**
 * 发送邮件
 * @param string $address
 * @param string $subject
 * @param string $message
 * @return array<br>
 * 返回格式：<br>
 * array(<br>
 * 	"error"=>0|1,//0代表出错<br>
 * 	"message"=> "出错信息"<br>
 * );
 */
function send_email($address, $subject, $message) {
    vendor('phpmailer');
    if (\think\Cache::has('email_config')) {
        $email_config = \think\Cache::get('email_config');
    } else {
        $email_config = Think\Db::name('system')->field('value')->where('name', 'email_config')->find();
        $email_config = unserialize($email_config['value']);
        \think\Cache::set('email_config', $email_config);
    }
    $mail = new \PHPMailer();
    // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();
    $mail->IsHTML(true);
    // 设置邮件的字符编码，若不指定，则为'UTF-8'
    $mail->CharSet = 'UTF-8';
    // 添加收件人地址，可以多次使用来添加多个收件人
    $mail->AddAddress($address);
    // 设置邮件正文
    $mail->Body = $message;
    // 设置邮件头的From字段。
    $mail->From = $email_config['address'];
    // 设置发件人名字
    $mail->FromName = $email_config['sender'];
    // 设置邮件标题
    $mail->Subject = $subject;
    // 设置SMTP服务器。
    $mail->Host = $email_config['smtp'];
    //by Rainfer
    // 设置SMTPSecure。 链接方式
    $Secure = @$email_config['smtpsecure'];
    $mail->SMTPSecure = empty($Secure) ? '' : $Secure;
    // 设置SMTP服务器端口。
    $port = $email_config['smtp_port'];
    $mail->Port = empty($port) ? "25" : $port;
    // 设置为"需要验证"
    $mail->SMTPAuth = true;
    // 设置用户名和密码。
    $mail->Username = $email_config['loginname'];
    $mail->Password = $email_config['password'];
    // 发送邮件。
    if (!$mail->Send()) {
        $mailerror = $mail->ErrorInfo;
        return array("status" => 1, "message" => $mailerror);
    } else {
        return array("status" => 0, "message" => "success");
    }
}

/**
 * 加密函数
 * @param string $txt 需要加密的字符串
 * @param string $key 密钥
 * @return string 返回加密结果
 */
function encrypt($txt, $key = '') {
    if (empty($txt))
        return $txt;
    if (empty($key))
        $key = md5(\think\Config::get('salt'));
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $nh1 = rand(0, 64);
    $nh2 = rand(0, 64);
    $nh3 = rand(0, 64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;
    $i = 0;
    while (isset($key{$i}))
        $knum +=ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key . $ch1) . $ch2 . $ikey) . $ch3), $nhnum % 8, $knum % 8 + 16);
    $txt = base64_encode(time() . '_' . $txt);
    $txt = str_replace(array('+', '/', '='), array('-', '_', '.'), $txt);
    $tmp = '';
    $j = 0;
    $k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i = 0; $i < $tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum + strpos($chars, $txt{$i}) + ord($mdKey{$k++})) % 64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp, $ch3, $nh2 % ++$tmplen, 0);
    $tmp = substr_replace($tmp, $ch2, $nh1 % ++$tmplen, 0);
    $tmp = substr_replace($tmp, $ch1, $knum % ++$tmplen, 0);
    return $tmp;
}

/**
 * 解密函数
 * @param string $txt 需要解密的字符串
 * @param string $key 密匙
 * @return string 字符串类型的返回结果
 */
function decrypt($txt, $key = '', $ttl = 0) {
    if (empty($txt))
        return $txt;
    if (empty($key))
        $key = md5(\think\Config::get('salt'));

    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $knum = 0;
    $i = 0;
    $tlen = @strlen($txt);
    while (isset($key{$i}))
        $knum +=ord($key{$i++});
    $ch1 = @$txt{$knum % $tlen};
    $nh1 = strpos($chars, $ch1);
    $txt = @substr_replace($txt, '', $knum % $tlen--, 1);
    $ch2 = @$txt{$nh1 % $tlen};
    $nh2 = @strpos($chars, $ch2);
    $txt = @substr_replace($txt, '', $nh1 % $tlen--, 1);
    $ch3 = @$txt{$nh2 % $tlen};
    $nh3 = @strpos($chars, $ch3);
    $txt = @substr_replace($txt, '', $nh2 % $tlen--, 1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key . $ch1) . $ch2 . $ikey) . $ch3), $nhnum % 8, $knum % 8 + 16);
    $tmp = '';
    $j = 0;
    $k = 0;
    $tlen = @strlen($txt);
    $klen = @strlen($mdKey);
    for ($i = 0; $i < $tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars, $txt{$i}) - $nhnum - ord($mdKey{$k++});
        while ($j < 0)
            $j+=64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-', '_', '.'), array('+', '/', '='), $tmp);
    $tmp = trim(base64_decode($tmp));

    if (preg_match("/\d{10}_/s", substr($tmp, 0, 11))) {
        if ($ttl > 0 && (time() - substr($tmp, 0, 11) > $ttl)) {
            $tmp = null;
        } else {
            $tmp = substr($tmp, 11);
        }
    }
    return $tmp;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = & $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = & $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = & $refer[$parentId];
                    $parent[$child][] = & $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 产生随机数串
 * @param integer $len 随机数字长度
 * @return string
 */
function randString($len = 6) {
    $chars = str_repeat('0123456789', 3);
    // 位数过长重复字符串一定次数
    $chars = str_repeat($chars, $len);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);
    return $str;
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[] = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children') {
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid) {
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 *  获取用户登录状态
 */
function IsLogin() {
    $uid = \think\Session::get('user_id');
    if ($uid) {
        defined('UID') or define('UID', $uid);
    } else {
        defined('UID') or define('UID', 0);
    }
}

/**
 *  获取管理员登录状态
 */
function IsAdminLogin() {
    $admin_id = \think\Session::get('admin_id');
    if ($admin_id) {
        defined('ADMIN_UID') or define('ADMIN_UID', $admin_id);
    } else {
        defined('ADMIN_UID') or define('ADMIN_UID', 0);
    }
}

/*
 * 隐藏号码中间四位
 */

function hidden_mobile($str) {
    return substr_replace($str, '****', 3, 4);
}

/**
 * 获取客户端IP地址
 * @param integer   $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean   $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function ip($type = 0, $adv = false) {
    $type = $type ? 1 : 0;
    static $ip = null;
    if (null !== $ip) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim(current($arr));
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
    return $ip[$type];
}

/**
 * @param $data
 * @return bool
 * 是否为序列化数据
 */
function is_serialized($data) {
    $data = trim($data);
    if ('N;' == $data)
        return true;
    if (!preg_match('/^([adObis]):/', $data, $badions))
        return false;
    switch ($badions[1]) {
        case 'a' :
        case 'O' :
        case 's' :
            if (preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data))
                return true;
            break;
        case 'b' :
        case 'i' :
        case 'd' :
            if (preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data))
                return true;
            break;
    }
    return false;
}

/**
 * 设置动态配置
 * @param array $data <br>如：["debug"=>'false'];
 * @return boolean
 */
function itkee_set_dynamic_config($data) {
    if (!is_array($data)) {
        return false;
    }
    $configFile = ITKEE_ROOT . "data/conf/config.php";
    if (file_exists($configFile)) {
        $configs = include $configFile;
    } else {
        $configs = [];
    }

    $configs = array_merge($configs, $data);
    $result = file_put_contents($configFile, "<?php\treturn " . var_export($configs, true) . ";");

    return $result;
}

/*
 * CURL GET
 */

/**
 * 发送HTTP请求方法
 * @param  string $url    请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function curl_http($url, $params, $method = 'GET', $header = array(), $multi = false) {
    if (empty($header)) {
        $header = array("Content-type: application/json; charset=utf-8");
    }
    $opts = array(
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_FOLLOWLOCATION => 1
    );
    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            return false;
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error)
        return false;
    return $data;
}

//生成一串随机乱码

function getRandChar($length = 32) {
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; //大小写字母以及数字
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $length; $i++) {
        $str.=$strPol[rand(0, $max)];
    }
    return $str;
}

//独立的redis
function common_redis() {
    static $redis;
    if (is_null($redis)) {
        if (!(extension_loaded('redis'))) {
            return error(-1, 'PHP 未安装 redis 扩展');
        }
        $config = config('cache');
        if (strtolower($config['type']) !== 'redis') {
            throw new \Exception('未配置 redis, 请检查缓存中参数设置');
        }

        if (empty($config['host'])) {
            $config['host'] = '127.0.0.1';
        }
        if (empty($config['port'])) {
            $config['port'] = '6379';
        }
        $redis_temp = new \Redis();
        if (!empty($config['persistent'])) {
            $connect = $redis_temp->pconnect($config['host'], $config['port'], $config['timeout']);
        } else {
            $connect = $redis_temp->connect($config['host'], $config['port'], $config['timeout']);
        }
        if (!($connect)) {
            throw new \Exception(-1, 'redis 连接失败, 请检查 data/config.php 中参数设置');
        }
        if (!(empty($config['password']))) {
            $redis_temp->auth($config['password']);
        }
        if (!(empty($config['select']))) {
            $redis_temp->select($config['select']);
        }
        $ping = $redis_temp->ping();
        if ($ping != '+PONG') {
            throw new \Exception(-1, 'redis 无法正常工作，请检查 redis 服务');
        }
        $redis = $redis_temp;
    }
    return $redis;
}

//统计一个值在某个数组内出现的次数
function GetNumberOfK($data, $k) {
    $count = 0;
    foreach ($data as $key => $v) {
        if ($v == $k) {
            $count++;
        }
    }
    return $count;
}

/**
 * 数组分页函数  核心函数  array_slice   
 * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中   
 * $count   每页多少条数据   
 * $page   当前第几页   
 * $array   查询出来的所有数组   
 * order 0 - 不变     1- 反序   
 */
function page_array($page, $array, $order = 0) {
    global $countpage; #定全局变量      
    $psize = config('paginate.list_rows') ? config('paginate.list_rows') : 20;
    $start = ($page - 1) * $psize; #计算每次分页的开始位置      
    if ($order == 1) {
        $array = array_reverse($array);
    }
    $totals = count($array);
    $countpage = ceil($totals / $psize); #计算总页面数      
    $pagedata = array_slice($array, $start, $psize);
    return $pagedata;  #返回查询数据      
}

function get_http_header($num) {
    $http = array(
        100 => "HTTP/1.1 100 Continue",
        101 => "HTTP/1.1 101 Switching Protocols",
        200 => "HTTP/1.1 200 OK",
        201 => "HTTP/1.1 201 Created",
        202 => "HTTP/1.1 202 Accepted",
        203 => "HTTP/1.1 203 Non-Authoritative Information",
        204 => "HTTP/1.1 204 No Content",
        205 => "HTTP/1.1 205 Reset Content",
        206 => "HTTP/1.1 206 Partial Content",
        300 => "HTTP/1.1 300 Multiple Choices",
        301 => "HTTP/1.1 301 Moved Permanently",
        302 => "HTTP/1.1 302 Found",
        303 => "HTTP/1.1 303 See Other",
        304 => "HTTP/1.1 304 Not Modified",
        305 => "HTTP/1.1 305 Use Proxy",
        307 => "HTTP/1.1 307 Temporary Redirect",
        400 => "HTTP/1.1 400 Bad Request",
        401 => "HTTP/1.1 401 Unauthorized",
        402 => "HTTP/1.1 402 Payment Required",
        403 => "HTTP/1.1 403 Forbidden",
        404 => "HTTP/1.1 404 Not Found",
        405 => "HTTP/1.1 405 Method Not Allowed",
        406 => "HTTP/1.1 406 Not Acceptable",
        407 => "HTTP/1.1 407 Proxy Authentication Required",
        408 => "HTTP/1.1 408 Request Time-out",
        409 => "HTTP/1.1 409 Conflict",
        410 => "HTTP/1.1 410 Gone",
        411 => "HTTP/1.1 411 Length Required",
        412 => "HTTP/1.1 412 Precondition Failed",
        413 => "HTTP/1.1 413 Request Entity Too Large",
        414 => "HTTP/1.1 414 Request-URI Too Large",
        415 => "HTTP/1.1 415 Unsupported Media Type",
        416 => "HTTP/1.1 416 Requested range not satisfiable",
        417 => "HTTP/1.1 417 Expectation Failed",
        422 => "HTTP/1.1 422 Error Api",
        500 => "HTTP/1.1 500 Internal Server Error",
        501 => "HTTP/1.1 501 Not Implemented",
        502 => "HTTP/1.1 502 Bad Gateway",
        503 => "HTTP/1.1 503 Service Unavailable",
        504 => "HTTP/1.1 504 Gateway Time-out"
    );
    header($http[$num]);
}



//把秒数转换为时分秒的格式 
function secToTime_com($times) {
    $result = ' ';
    if ($times > 0) {
        $hour = floor($times / 3600);
        $minute = floor(($times - 3600 * $hour) / 60);
        $second = floor((($times - 3600 * $hour) - 60 * $minute) % 60);
        if ($hour > 0) {
            $result.=$hour . '小时 ';
        }
        if ($minute > 0) {
            $result.=$minute . ' 分钟 ';
        } elseif ($minute < 0 && $second > 0) {
            $result.=$second . ' 秒';
        }
    }
    return $result;
}

//两数组取最优(已排行好的)
function sortArrByManyField() {
    $args = func_get_args();
    if (empty($args)) {
        return null;
    }
    $arr = array_shift($args);
    if (!is_array($arr)) {
        throw new Exception("第一个参数不为数组");
    }
    foreach ($args as $key => $field) {
        if (is_string($field)) {
            $temp = array();
            foreach ($arr as $index => $val) {
                $temp[$index] = $val[$field];
            }
            $args[$key] = $temp;
        }
    }
    $args[] = &$arr; //引用值
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}

//秒数转为时分秒
function changeTimeType($seconds) {
    if ($seconds > 3600) {
        $hours = intval($seconds / 3600);
        $minutes = $seconds % 3600;
        $time = $hours . ":" . gmstrftime('%M:%S', $minutes);
    } else {
        $time = gmstrftime('%H:%M:%S', $seconds);
    }
    return $time;
}

//计算数组连续次数
function count_array_continuity($arr, $count_num) {
    $arr_unique = array_unique($arr);
    array_push($arr, 'aa');
    foreach ($arr_unique as $v) {
        array_push($arr, $v);
    }
    $count_arr = [];
    $two_count = []; //每个连号节点统计数组
    $last_v = 0;
    foreach ($arr as $key => $v) {
        if ($v == $last_v) {
            if (empty($count_arr[$v])) {
                $count_arr[$v] = 2;
            } else {
                $count_arr[$v] ++;
            }
        } else {
            if (!empty($count_arr[$v]) && $count_arr[$v] > 1) { //如果之前就有统计重复了
                $s = [];
                $s['index'] = $v;
                $s['count'] = $count_arr[$v];
                $two_count[] = $s;
            }
            $count_arr[$v] = 1;
            $last_v = $v;
        }
    }
    $total = 0;
    foreach ($two_count as $key => $v) {
        if ($v['index'] == $count_num) {
            $total+=$v['count'];
        }
    }
    return $total;
}

//创建一个订单号
function createNO($prefix = 'SH') {
    $billno = date('YmdHis') . com_random(6, true);
    return $prefix . $billno;
}

//产生随机数
function com_random($length, $numeric = FALSE) {
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    if ($numeric) {
        $hash = '';
    } else {
        $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
        $length--;
    }
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

/**
 * 计算剩余天时分。 
 * $unixEndTime string 终止日期的Unix时间 
 */
function count_diff_date($unixEndTime = 0) {
    if ($unixEndTime <= time()) { // 如果过了活动终止日期  
        return ' 已过期';
    }
    // 使用当前日期时间到活动截至日期时间的毫秒数来计算剩余天时分  
    $time = $unixEndTime - time();

    $days = 0;
    if ($time >= 86400) { // 如果大于1天  
        $days = (int) ($time / 86400);
        $time = $time % 86400; // 计算天后剩余的毫秒数  
    }

    $xiaoshi = 0;
    if ($time >= 3600) { // 如果大于1小时  
        $xiaoshi = (int) ($time / 3600);
        $time = $time % 3600; // 计算小时后剩余的毫秒数  
    }

    $fen = (int) ($time / 60); // 剩下的毫秒数都算作分
    if ($days > 365) {
        return $days . ' 天';
    } elseif ($days > 1) {
        return $days . ' 天';
    } elseif ($days > 0) {
        return $days . ' 天' . $xiaoshi . '时';
    } elseif ($days == 0 && $xiaoshi > 1) {
        return $xiaoshi . ' 时';
    } elseif ($xiaoshi == 0) {
        return $fen . ' 分';
    }
}

//二维数组排序
function sortByMultiCols($rowset, $args) {
    $sortArray = array();
    $sortRule = '';
    foreach ($args as $sortField => $sortDir) {
        foreach ($rowset as $offset => $row) {
            $sortArray[$sortField][$offset] = $row[$sortField];
        }
        $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
    }
    if (empty($sortArray) || empty($sortRule)) {
        return $rowset;
    }
    eval('array_multisort(' . $sortRule . '$rowset);');
    return $rowset;
}

/*
 * 判断数组离散程度
 * variance 方差
 * square:标准差
 * lisan 离散程度
 */

function common_variance($arr) {
    $length = count($arr);
    if ($length == 0) {
        return array(0, 0);
    }
    $average = array_sum($arr) / $length;
    $count = 0;
    foreach ($arr as $v) {
        $count += pow($average - $v, 2);
    }
    $variance = $count / $length;
    $square = sqrt($variance);
    $lisan = $square / $average;
    return array('variance' => $variance, 'square' =>$square , 'average' => $average,'lisan'=>$lisan);
}
